package com.aaa.system.service.imp;

import com.aaa.entity.Role;
import com.aaa.entity.RoleMenu;
import com.aaa.entity.User;
import com.aaa.system.mapper.RoleMapper;
import com.aaa.system.mapper.UserMapper;
import com.aaa.system.service.RoleService;
import com.aaa.system.vo.RoleVo;
import com.aaa.utils.TokenUtils;
import com.aaa.utils.WebUtil;
import com.aaa.vo.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class RoleServiceImp implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 查询用户所具有的角色
     * 查询所有的角色信息
     * @param userId
     * @return
     */
    @Override
    public Result<Map<String, Object>> findUserRoleByUserId(Long userId) {
        //通过用户的id查询用户所具有的角色
        List<Role> userRoles=roleMapper.selectByUserId(userId);
        //查询所有的角色
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status",0);
        queryWrapper.eq("del_flag",0);
        List<Role> roles = roleMapper.selectList(queryWrapper);

        Map<String,Object> map = new HashMap<>();
        map.put("roles",roles);
        map.put("userRoles",userRoles);
        return new Result<>(200,"查询用户、角色成功",map);
    }

    /**
     * 修改用户的角色
     * @param userId
     * @param roleIds
     * @return
     */
    //开启事务
    @Transactional
    @Override
    public Result<String> shareRole(Long userId, Long[] roleIds) {
        //开启事务
        //先删除用户所有的角色
        roleMapper.deleteByUserId(userId);
        //添加用户所有的角色
        if (roleIds.length!=0){
            roleMapper.batchInsert(userId,roleIds);
        }
        return new Result<>(200,"角色分配成功");
    }

    @Override
    public Result<IPage<Role>> findAllData(RoleVo roleVo) {
        IPage page = new Page(roleVo.getCurrent(),roleVo.getSize());
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(roleVo.getRoleName())){
            queryWrapper.like("role_name",roleVo.getRoleName());
        }
        if (StringUtils.isNotBlank(roleVo.getRoleCode())){
            queryWrapper.like("role_code",roleVo.getRoleCode());
        }
        if (Objects.nonNull(roleVo.getStatus())){
            queryWrapper.eq("status",roleVo.getStatus());
        }
        if (Objects.nonNull(roleVo.getDateRange())&&roleVo.getDateRange().length==2){
            queryWrapper.between("create_time",roleVo.getDateRange()[0],roleVo.getDateRange()[1]);
        }
        queryWrapper.eq("del_flag",0);
        IPage page1 = roleMapper.selectPage(page, queryWrapper);
        return new Result<>(200,"查询角色信息成功",page1);
    }

    @Override
    public Result<Boolean> saveOrUpdateRole(Role role) {
        String token = WebUtil.getRequest().getHeader("token");
        String username = TokenUtils.getInfo(token).get("username").toString();
        //根据手机号进行查询
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone",username);
        queryWrapper.eq("status",0);
        queryWrapper.eq("del_flag",0);
        User userdata = userMapper.selectOne(queryWrapper);

        //如果角色id存在侧为修改  否则为添加
        if (Objects.nonNull(role.getRoleId())){//修改
            role.setUpdateTime(new Date());
            role.setUpdateBy(userdata.getUserName());
            int i = roleMapper.updateById(role);
            return new Result<>(200,"修改成功",i>0?true:false);
        }//添加
        role.setDelFlag("0");
        role.setCreateTime(new Date());
        role.setCreateBy(userdata.getUserName());
        int i = roleMapper.insert(role);
        return new Result<>(200,"添加成功",i>0?true:false);
    }

    @Transactional
    @Override
    public Result<Boolean> delOneRole(Long roleId) {
        Role role = new Role();
        role.setRoleId(roleId);
        role.setDelFlag("1");
        //可以删除
        //修改role表//删除user_role表信息
        int i = roleMapper.updateById(role);
        roleMapper.updRUByRoleId(roleId);
        return new Result<>(200,"角色删除成功",i>0?true:false);
    }

    @Override
    public List<RoleMenu> findMenuByRoleId(Long roleId) {
        List<RoleMenu> list =roleMapper.selectMenuByRoleId(roleId);
        return list;
    }

    @Transactional
    @Override
    public Result<Boolean> bachRole(Long[] roleIds) {
        //查询角色菜单表是否存在 不存在 可以删除 存在 不能删除
        List<RoleMenu> list =roleMapper.selectRM(roleIds);
        if (list.size()>0){//存在 不能删除
            return new Result<>(200,"某角色已使用菜单不能被删除",true);
        }
        //修改角色表
        roleMapper.updRoleDelFlag(roleIds);
        //修改role_menu表
        int i = roleMapper.delRMRole(roleIds);
        return new Result<>(200,"批量删除成功",i>0?true:false);
    }
}
